package com.jy.appmarket.adapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.jy.appmarket.R;
import com.jy.appmarket.download.DownloadActivity;
import com.jy.appmarket.download.DownloadActivity.AppAndDownloadListener;
import com.jy.appmarket.download.DownloadItem;
import com.jy.appmarket.download.DownloadService;
import com.jy.appmarket.download.DownloadUtils;
import com.jy.appmarket.model.AppInfoModel;
import com.jy.appmarket.utils.AsyncImageLoader;
import com.jy.appmarket.utils.LogUtil;
import com.jy.appmarket.utils.PackageUtils;
import com.jy.appmarket.widget.PinProgressButton;
import com.jy.appmarket.widget.PinProgressButton.DownloadState;

public class WindowAppAdapter extends BaseAdapter implements AppAndDownloadListener {
	public interface AppClickedListener {
		void onAppClicked(AppInfoModel app);
	}

	private AsyncImageLoader mImageLoader;
	private DownloadActivity mActivity;
	private List<AppInfoModel> mList;
	private Map<String, AppInfoModel> mMap;

	public WindowAppAdapter(DownloadActivity a, Activity activity) {
		mImageLoader = AsyncImageLoader.getInstance(a);
		mActivity = a;
	}

	public void append(List<AppInfoModel> apps) {
		if (mList == null) {
			mList = new ArrayList<AppInfoModel>();
			mMap = new HashMap<String, AppInfoModel>();
		} else {
			mList.clear();
		}

		for (AppInfoModel app : apps) {
			if (!TextUtils.isEmpty(app.getDownloadUrl())) {
				String dlId = DownloadUtils.generateDownloadId(app.getPackageName(),
						app.getVersionCode());
				DownloadItem dlItem = mActivity.getDownloadById(dlId);
				long len = DownloadUtils.getDownloadedBytes(dlId);

				app.setDownloadId(dlId);
				app.setDownloadedSize(len);
				app.setmDownloadModel(dlItem);
				app.setState(mActivity.getDownloadStatus(dlId, app.getPackageName(),
						app.getVersionCode()));
				mList.add(app);
				mMap.put(dlId, app);
			} else {
				mList.add(app);
			}
		}
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		final AppInfoModel app = mList.get(position);
		final WindowViewHolder holder;
		if (convertView == null) {
			convertView = View.inflate(mActivity, R.layout.item_window_app, null);
			holder = new WindowViewHolder();
			holder.icon = convertView.findViewById(R.id.iv_icon);
			holder.title = convertView.findViewById(R.id.tv_name);
			holder.download = convertView.findViewById(R.id.iv_downloaded_icon);
			holder.progress = convertView.findViewById(R.id.pb_downloading);
			holder.progress.setVisibility(View.GONE);
			convertView.setTag(holder);
		} else {
			holder = (WindowViewHolder) convertView.getTag();
		}

		if (position == mList.size() - 1) {
			holder.download.setVisibility(View.GONE);
			holder.title.setText(" ");
			holder.icon.setImageResource(R.drawable.add_more_selector);
			holder.progress.setVisibility(View.GONE);
			return convertView;

		} else {

			if (app.isInstalledApp() || (position == mList.size() - 1)) {
				holder.download.setVisibility(View.GONE);
				try {
					PackageManager pm = mActivity.getPackageManager();
					Drawable drawable = pm.getApplicationIcon(app.getPackageName());
					holder.icon.setImageDrawable(drawable);
				} catch (Exception e) {
					e.printStackTrace();
				}

			} else {
				holder.download.setVisibility(View.VISIBLE);
				mImageLoader.displayImage(app.getPic(), holder.icon,
						R.drawable.default_loading_icon, false);
			}
			holder.title.setText(app.getName());
			setProgressButton(holder, app);
			return convertView;
		}
	}

	private void setProgressButton(WindowViewHolder holder, AppInfoModel app) {
		int status = mActivity.getDownloadStatus(app.getDownloadId(), app.getPackageName(),
				app.getVersionCode());

		switch (status) {
		case DownloadService.STATUS_CAN_INSTALL:
			holder.title.setText("下载完成");
			holder.download.setVisibility(View.GONE);
			holder.progress.setVisibility(View.GONE);
			break;

		case DownloadService.STATUS_PAUSED_BY_ERROR:
			holder.title.setText("下载错误");
			holder.download.setVisibility(View.GONE);
			holder.progress.setDownloadState(DownloadState.DOWNLOAD_ERROR);
			holder.progress.setProgress(0);
			holder.progress.setVisibility(View.VISIBLE);
			break;

		case DownloadService.STATUS_INSTALLED:
			holder.title.setText(app.getName());
			holder.download.setVisibility(View.GONE);
			holder.progress.setVisibility(View.GONE);
			app.setInstalledApp(true);
			break;

		case DownloadService.STATUS_NO_STATUS:
			holder.title.setText(app.getName());
			holder.download.setVisibility(View.VISIBLE);
			holder.progress.setVisibility(View.GONE);
			break;

		case DownloadService.STATUS_PAUSED_BY_MOBILE_NETWORK:
			holder.title.setText("等待wifi");
			holder.download.setVisibility(View.GONE);
			holder.progress.setProgress(0);
			holder.progress.setDownloadState(DownloadState.DOWNLOAD_WAITING);
			holder.progress.setVisibility(View.VISIBLE);
			break;

		case DownloadService.STATUS_PAUSED_BY_USER:
			holder.title.setText("暂停");
			holder.download.setVisibility(View.GONE);
			holder.progress.setProgress(getProgress(app));
			holder.progress.setDownloadState(DownloadState.DOWNLOAD_PAUSE);
			holder.progress.setVisibility(View.VISIBLE);
			break;

		case DownloadService.STATUS_DOWNLOADING:
			holder.title.setText("下载中");
			holder.download.setVisibility(View.GONE);
			holder.progress.setVisibility(View.VISIBLE);
			holder.progress.setDownloadState(DownloadState.DEFAULT);
			holder.progress.setProgress(getProgress(app));
			break;
		case DownloadService.STATUS_PREPARE_TO_DOWNLOAD:
		case DownloadService.STATUS_PREPARE_TO_STOP:
			holder.title.setText("下载中");
			holder.download.setVisibility(View.GONE);
			holder.progress.setVisibility(View.VISIBLE);
			holder.progress.setDownloadState(DownloadState.DEFAULT);
			holder.progress.setProgress(getProgress(app));
			break;
		case DownloadService.STATUS_INSTALLING:
			holder.title.setText("安装中");
			holder.download.setVisibility(View.GONE);
			holder.progress.setVisibility(View.GONE);
			break;
		case DownloadService.STATUS_PENDING:
			holder.title.setText("等待中");
			holder.download.setVisibility(View.GONE);
			holder.progress.setProgress(0);
			holder.progress.setVisibility(View.VISIBLE);
			holder.progress.setDownloadState(DownloadState.DOWNLOAD_WAITING);
			break;
		case DownloadService.STATUS_DOWNLOAD_OUT_OF_DATE:
			holder.title.setText(app.getName());
			holder.progress.setVisibility(View.GONE);
			if (PackageUtils.isPackageInstalled(mActivity, app.getPackageName())) {
				holder.download.setVisibility(View.GONE);
				app.setInstalledApp(true);
			} else {
				holder.download.setVisibility(View.VISIBLE);
			}
			break;
		case DownloadService.STATUS_NEED_TO_UPDATE: // widget中，不提供升级功能。
			holder.title.setText(app.getName());
			holder.download.setVisibility(View.GONE);
			holder.progress.setVisibility(View.GONE);
			app.setInstalledApp(true);
			break;
		default:
			// LogUtil.w(TAG, "unknown status:" + app);
			break;
		}
	}

	private int getProgress(AppInfoModel app) {
		long total = app.getmDownloadModel().getTotalSize();
		if (total == 0) {
			total = Long.MAX_VALUE;
			LogUtil.w("currentPoint", "total is 0");
		}

		int per = (int) (app.getDownloadedSize() * 100.0 / total);

		if (per > 100) {
			per = 100;
		} else if (per < 0) {
			per = 0;
		}
		return per;
	}

	private static final class WindowViewHolder {
		private ImageView icon;
		private ImageView download;
		private TextView title;
		private PinProgressButton progress;
	}

	@Override
	public int getCount() {
		return mList.size();
	}

	@Override
	public Object getItem(int position) {
		return mList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	// @Override
	// public void onPackageChanged(String action, String pkgName) {
	// if (mList == null) {
	// return;
	// }
	// AppInfoModel app = null;
	// for (AppInfoModel a : mList) {
	// if (pkgName.equals(a.getPackageName())) {
	// app = a;
	// break;
	// }
	// }
	// if (app == null || app.getDownloadUrl() == null) {
	// return;
	// }
	// String id = FileDownloadService.getDownloadId(app.getPackageName());
	// FileDownloadModel fdm = FileDownloadService.getDownloadById(mActivity,
	// id);
	// app.setDownloadModel(fdm);
	// app.setState(mActivity.getDownloadStatus(app));
	//
	// notifyDataSetChanged();
	// }

	@Override
	public void onDownloadChanged(DownloadItem fdm) {
		LogUtil.d(
				"currentPoint",
				"onDownloadChanged:" + fdm.getName() + "  "
						+ DownloadService.getStatusString(fdm.getStatus()));
		AppInfoModel app = mMap.get(fdm.getId());
		if (app != null) {
			String id = DownloadUtils
					.generateDownloadId(app.getPackageName(), app.getVersionCode());
			long len = DownloadUtils.getDownloadedBytes(id);
			app.setDownloadedSize(len);
			app.setmDownloadModel(fdm);
			app.setState(mActivity.getDownloadStatus(id, app.getPackageName(), app.getVersionCode()));
			if (app.getState() == DownloadService.STATUS_PAUSED_BY_ERROR) {
				Toast.makeText(mActivity, app.getName() + "下载错误", Toast.LENGTH_SHORT).show();
			}
			notifyDataSetChanged();
		}
	}

	@Override
	public void onProgressChanged(String id, long downloaded, long speed) {
		AppInfoModel app = mMap.get(id);

		if (app == null) { // add by toby, 下载管理中通知的下载任务是所有榜单的下载任务，在这里可能不存在
			return;
		}

		app.setDownloadedSize(downloaded);
		notifyDataSetChanged();
	}

	@Override
	public void onPackageInstalled(String pkgName) {
		if (mList == null) {
			return;
		}
		AppInfoModel app = null;
		for (AppInfoModel a : mList) {
			if (pkgName.equals(a.getPackageName())) {
				app = a;
				break;
			}
		}
		if (app == null || app.getDownloadUrl() == null) {
			return;
		}
		String dlId = DownloadUtils.generateDownloadId(app.getPackageName(), app.getVersionCode());
		DownloadItem dlItem = mActivity.getDownloadById(dlId);
		app.setmDownloadModel(dlItem);
		app.setState(mActivity.getDownloadStatus(dlId, app.getPackageName(), app.getVersionCode()));

		notifyDataSetChanged();

	}

	@Override
	public void onPackageUninstalled(String pkgName) {
		if (mList == null) {
			return;
		}
		AppInfoModel app = null;
		for (AppInfoModel a : mList) {
			if (pkgName.equals(a.getPackageName())) {
				app = a;
				break;
			}
		}
		if (app == null || app.getDownloadUrl() == null) {
			return;
		}
		String dlId = DownloadUtils.generateDownloadId(app.getPackageName(), app.getVersionCode());
		DownloadItem dlItem = mActivity.getDownloadById(dlId);
		app.setmDownloadModel(dlItem);
		app.setState(mActivity.getDownloadStatus(dlId, app.getPackageName(), app.getVersionCode()));

		notifyDataSetChanged();
	}

	@Override
	public void onDownloadCreated(DownloadItem di) {
		// LogUtil.d(
		// "WindowAppActivity",
		// "onDownloadCreated:" + di.getName() + "  "
		// + DownloadService.getStatusString(di.getStatus()));
		AppInfoModel app = mMap.get(di.getId());

		if (app == null) {
			return;
		}
		String id = DownloadUtils.generateDownloadId(app.getPackageName(), app.getVersionCode());
		long len = DownloadUtils.getDownloadedBytes(id);
		app.setDownloadedSize(len);
		app.setmDownloadModel(di);
		app.setState(mActivity.getDownloadStatus(id, app.getPackageName(), app.getVersionCode()));
		if (app.getState() == DownloadService.STATUS_PAUSED_BY_ERROR) {
			Toast.makeText(mActivity, app.getName() + "下载错误", Toast.LENGTH_SHORT).show();
		}
		notifyDataSetChanged();
	}

	@Override
	public void onDownloadRemoved(String id) {
		AppInfoModel app = mMap.get(id);
		if (app != null) {
			app.setmDownloadModel(null);
			app.setCurrentDownloadSize(0);
			app.setState(DownloadService.STATUS_NO_STATUS);
			notifyDataSetChanged();
		}
	}
}
